package leetcode.code278.FirstBadVersion;

public class Solution2 implements IFirstBadVersion {

	private int badVersion;

	private VersionControl versionControl;

	public Solution2(int badVersion) {
		super();
		this.badVersion = badVersion;
		versionControl = new VersionControl(badVersion);
	}

	public static void main(String[] args) {
		myDebug(5,4);
		myDebug(2,2);
	}

	public static void myDebug(int n, int badVersion) {
		IFirstBadVersion ifbv = new Solution2(badVersion);
		int result = ifbv.firstBadVersion(n);
		System.out.println(result);
	}
	@Override
	public int firstBadVersion(int n) {
		int left = 1;
		int right = n;
		int midle = 0;
		while (left < right) {//边界去掉
			midle = left + (right - left) /2;
			if(isBadVersion(midle)) {
				right = midle;// 去掉-1 答案在区间 [left, mid] 中
			}else {
				left = midle + 1;// 答案在区间 [mid+1, right] 中
			}
		}
		return left;
	}

	private boolean isBadVersion(int n) {
		return versionControl.isBadVersion(n);
	}

}
